<template>
  <div class="habit-container">
    <!-- 添加习惯按钮 -->
    <div class="add-habit-button">
      <el-button type="primary" @click="showAddHabitDialog">
        <el-icon><Plus /></el-icon>
        添加新习惯
      </el-button>
    </div>

    <!-- 习惯列表 -->
    <div class="habits-list">
      <el-card v-for="habit in habits" :key="habit.id" class="habit-card">
        <div class="habit-header">
          <div class="habit-info">
            <h3>{{ habit.habitName }}</h3>
            <el-tag :type="getLevelType(habit.habitLevel)">Lv.{{ habit.habitLevel }}</el-tag>
            <el-tag size="small" :type="getDifficultyType(habit.difficulty)">
              {{ getDifficultyText(habit.difficulty) }}
            </el-tag>
          </div>
          <el-button 
            type="success" 
            @click="showCheckInDialog(habit)"
          >
            打卡
          </el-button>
        </div>
        
        <div class="habit-progress">
          <el-progress 
            :percentage="calculateProgress(habit)" 
            :status="getProgressStatus(habit)"
          />
          <div class="progress-info">
            <span>已完成 {{ habit.completedCount }} 次</span>
            <span>目标 {{ habit.targetCount }} 次</span>
          </div>
        </div>

        <div class="habit-details">
          <div class="detail-item">
            <el-icon><Timer /></el-icon>
            <span>触发场景：{{ habit.habitTrigger || '未设置' }}</span>
          </div>
          <div class="detail-item">
            <el-icon><Present /></el-icon>
            <span>奖励：{{ habit.reward || '未设置' }}</span>
          </div>
        </div>

        <div class="habit-grid">
          <div 
            v-for="(item, index) in habit.targetCount" 
            :key="index"
            class="grid-item"
            :class="{ 'completed': index < habit.completedCount }"
          >
            <el-icon v-if="index < habit.completedCount"><Check /></el-icon>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 添加习惯弹窗 -->
    <el-dialog
      v-model="addHabitDialogVisible"
      title="添加新习惯"
      width="500px"
    >
      <el-form 
        :model="newHabit" 
        label-width="100px"
        class="add-habit-form"
      >
        <el-form-item label="习惯名称">
          <el-input v-model="newHabit.habitName" placeholder="请输入习惯名称" />
        </el-form-item>
        <el-form-item label="目标次数">
          <el-input-number v-model="newHabit.targetCount" :min="1" :max="1000" />
        </el-form-item>
        <el-form-item label="难度等级">
          <el-select v-model="newHabit.difficulty" placeholder="选择难度" style="width: 100%">
            <el-option label="非常简单" value="very-easy" />
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
        </el-form-item>
        <el-form-item label="触发场景">
          <el-input 
            v-model="newHabit.habitTrigger" 
            placeholder="例如：早上起床后、午休时间、下班后"
          />
        </el-form-item>
        <el-form-item label="奖励机制">
          <el-input 
            v-model="newHabit.reward" 
            placeholder="例如：完成一次奖励自己看一集剧"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addHabitDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addHabit">确认添加</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 打卡弹窗 -->
    <el-dialog
      v-model="checkInDialogVisible"
      title="完成打卡"
      width="30%"
    >
      <div class="check-in-content">
        <p>你正在完成习惯：{{ selectedHabit?.habitName }}</p>
        <p>当前进度：{{ selectedHabit?.completedCount }}/{{ selectedHabit?.targetCount }}</p>
        <p>当前等级：Lv.{{ selectedHabit?.habitLevel }}</p>
        <p>触发场景：{{ selectedHabit?.habitTrigger || '未设置' }}</p>
        <p>完成奖励：{{ selectedHabit?.reward || '未设置' }}</p>
        <div class="check-in-actions">
          <el-button @click="checkInDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="completeCheckIn">确认完成</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Check, Timer, Present, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getHabitList, createHabit, updateHabitCount, updateHabit } from '@/api/habit'
import emitter from '@/utils/eventBus'

// 弹窗控制
const addHabitDialogVisible = ref(false)
const checkInDialogVisible = ref(false)
const selectedHabit = ref(null)

// 新习惯表单数据
const newHabit = ref({
  habitName: '',
  targetCount: 60,
  difficulty: 'medium',
  habitTrigger: '',
  reward: ''
})

// 习惯列表数据
const habits = ref([])

// 获取习惯列表
const fetchHabits = async () => {
  try {
    const params = {
      pageNum: 1,
      pageSize: 100 // 获取较多数据，实际项目中可能需要分页
    }
    const res = await getHabitList(params)
    if (res.data.records) {
    console.log(res.data.records)
      habits.value = res.data.records
    }
  } catch (error) {
    ElMessage.error('获取习惯列表失败')
    console.error('获取习惯列表失败:', error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchHabits()
})

// 显示添加习惯弹窗
const showAddHabitDialog = () => {
  addHabitDialogVisible.value = true
}

// 添加新习惯
const addHabit = async () => {
  if (!newHabit.value.habitName) {
    ElMessage.warning('请输入习惯名称')
    return
  }

  try {
    const habitData = {
      habitName: newHabit.value.habitName,
      targetCount: newHabit.value.targetCount,
      habitLevel: 1,
      difficulty: newHabit.value.difficulty,
      habitTrigger: newHabit.value.habitTrigger,
      reward: newHabit.value.reward
    }

    await createHabit(habitData)
    ElMessage.success('添加成功')
    addHabitDialogVisible.value = false
    
    // 重置表单
    newHabit.value = {
      habitName: '',
      targetCount: 60,
      difficulty: 'medium',
      habitTrigger: '',
      reward: ''
    }
    
    // 重新获取列表
    await fetchHabits()
  } catch (error) {
    ElMessage.error('添加习惯失败')
    console.error('添加习惯失败:', error)
  }
}

// 显示打卡弹窗
const showCheckInDialog = (habit) => {
  selectedHabit.value = habit
  checkInDialogVisible.value = true
}

// 完成打卡
const completeCheckIn = async () => {
  if (!selectedHabit.value) return

  try {
    const habit = selectedHabit.value
    const newCompletedCount = habit.completedCount + 1
    
    // 更新完成数量
    const res = await updateHabitCount({
      id: habit.id,
      completedCount: newCompletedCount
    })
    
    // 检查是否需要升级
    if (newCompletedCount >= habit.targetCount) {
      // 更新等级
      await updateHabit({
        id: habit.id,
        habitLevel: habit.habitLevel + 1,
        completedCount: 0
      })
      ElMessage.success(`恭喜！${habit.habitName} 已升级到 Lv.${habit.habitLevel + 1}`)
      // 在数据更新后触发刷新header事件
      emitter.emit('refreshHeader')
    } else {
      const reward = res.data.data;
      if(reward === "很遗憾没有获得积分"){
        ElMessage.warning(reward)
      }else{
        ElMessage.success(reward)
      }
      // 在数据更新后触发刷新header事件
      emitter.emit('refreshHeader')
    }

    checkInDialogVisible.value = false
    // 重新获取列表以更新数据
    await fetchHabits()
  } catch (error) {
    ElMessage.error('打卡失败')
    console.error('打卡失败:', error)
  }
}

// 计算进度
const calculateProgress = (habit) => {
  return Math.round((habit.completedCount / habit.targetCount) * 100)
}

// 获取进度状态
const getProgressStatus = (habit) => {
  const progress = calculateProgress(habit)
  if (progress >= 100) return 'success'
  if (progress >= 50) return 'warning'
  return ''
}

// 获取等级标签类型
const getLevelType = (level) => {
  if (level >= 5) return 'danger'
  if (level >= 3) return 'warning'
  return 'success'
}

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  const types = {
    'very-easy': 'success',
    'easy': 'info',
    'medium': 'warning',
    'hard': 'danger'
  }
  return types[difficulty] || 'info'
}

// 获取难度文本
const getDifficultyText = (difficulty) => {
  const texts = {
    'very-easy': '非常简单',
    'easy': '简单',
    'medium': '中等',
    'hard': '困难'
  }
  return texts[difficulty] || '未知'
}
</script>

<style scoped>
.habit-container {
  max-width: 1200px;
  margin: 0 auto;
}

.add-habit-button {
  margin-bottom: 24px;
  display: flex;
  justify-content: flex-end;
}

.add-habit-form {
  padding: 20px 0;
}

.habits-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.habit-card {
  transition: all 0.3s ease;
}

.habit-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.habit-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.habit-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.habit-info h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.habit-progress {
  margin-bottom: 16px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.habit-details {
  margin: 16px 0;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.habit-grid {
  display: grid;
  grid-template-columns: repeat(10, 1fr);
  gap: 8px;
  margin-top: 16px;
}

.grid-item {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background: #f5f7fa;
  font-size: 12px;
  color: #606266;
  transition: all 0.3s ease;
}

.grid-item.completed {
  background: #67c23a;
  color: white;
}

.check-in-content {
  text-align: center;
}

.check-in-content p {
  margin: 10px 0;
}

.check-in-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media screen and (max-width: 768px) {
  .habits-list {
    grid-template-columns: 1fr;
  }

  /* 移动端弹窗样式 */
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto !important;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    margin: 0 !important;
  }

  :deep(.el-dialog__body) {
    padding: 15px;
  }

  .check-in-content {
    padding: 10px;
  }

  .check-in-content p {
    margin: 8px 0;
    font-size: 14px;
  }

  .check-in-actions {
    margin-top: 15px;
    flex-direction: column;
    gap: 8px;
  }

  .check-in-actions .el-button {
    width: 100%;
  }

  /* 添加习惯弹窗样式 */
  .add-habit-form {
    padding: 10px 0;
  }

  :deep(.el-form-item__label) {
    font-size: 14px;
  }

  :deep(.el-input__wrapper),
  :deep(.el-select) {
    width: 100%;
  }

  .dialog-footer {
    flex-direction: column;
    gap: 8px;
  }

  .dialog-footer .el-button {
    width: 100%;
  }
}
</style> 